from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import Supplier, db
from utils import error, success
from datetime import datetime

supplier_api = Blueprint('supplier_api', __name__, url_prefix='/api/suppliers')

@supplier_api.route('/', methods=['GET'])
@jwt_required()
def get_suppliers():
    """获取供应商列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('page_size', 10, type=int)
        search = request.args.get('search', '')
        
        query = Supplier.query
        
        # 搜索过滤
        if search:
            query = query.filter(
                Supplier.name.contains(search) | 
                Supplier.contact_person.contains(search) |
                Supplier.phone.contains(search) |
                Supplier.email.contains(search)
            )
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        suppliers = []
        for supplier in pagination.items:
            suppliers.append({
                'id': supplier.id,
                'name': supplier.name,
                'contact_person': supplier.contact_person,
                'phone': supplier.phone,
                'email': supplier.email,
                'address': supplier.address,
                'created_at': supplier.created_at.isoformat(),
                'updated_at': supplier.updated_at.isoformat()
            })
        
        return success(data={
            'suppliers': suppliers,
            'total': pagination.total,
            'pagination': {
                'page': pagination.page,
                'page_size': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(500, f'Failed to get supplier list: {str(e)}').to_response()


@supplier_api.route('/', methods=['POST'])
@jwt_required()
def create_supplier():
    """创建供应商"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return error(code=400, msg='供应商名称不能为空').to_response()
        
        # 创建供应商
        supplier = Supplier(
            name=data['name'],
            contact_person=data.get('contact_person', ''),
            phone=data.get('phone', ''),
            email=data.get('email', ''),
            address=data.get('address', '')
        )
        
        db.session.add(supplier)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '供应商创建成功',
            'data': {
                'id': supplier.id,
                'name': supplier.name
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return error(500, f'Failed to create supplier: {str(e)}').to_response()

@supplier_api.route('/<int:supplier_id>', methods=['PUT'])
@jwt_required()
def update_supplier(supplier_id):
    """更新供应商"""
    try:
        supplier = Supplier.query.get_or_404(supplier_id)
        data = request.get_json()
        
        # 更新字段
        if 'name' in data:
            supplier.name = data['name']
        if 'contact_person' in data:
            supplier.contact_person = data['contact_person']
        if 'phone' in data:
            supplier.phone = data['phone']
        if 'email' in data:
            supplier.email = data['email']
        if 'address' in data:
            supplier.address = data['address']
        
        supplier.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '供应商更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return error(500, f'Failed to update supplier: {str(e)}').to_response()

@supplier_api.route('/<int:supplier_id>', methods=['DELETE'])
@jwt_required()
def delete_supplier(supplier_id):
    """删除供应商"""
    try:
        supplier = Supplier.query.get_or_404(supplier_id)
        
        # 检查是否有关联的商品
        if supplier.products:
            return error(code=400, msg='无法删除有关联商品的供应商').to_response()
        
        db.session.delete(supplier)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '供应商删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return error(500, f'Failed to delete supplier: {str(e)}').to_response()


